package org.boulderfoodrescue.webapp.client.googlemap;

import org.boulderfoodrescue.webapp.client.googlemap.custominfopanel.InfoPanel;
import org.boulderfoodrescue.webapp.shared.Location;

import com.google.gwt.maps.client.InfoWindowContent;
import com.google.gwt.maps.client.MapType;
import com.google.gwt.maps.client.MapWidget;
import com.google.gwt.maps.client.event.MarkerClickHandler;
import com.google.gwt.maps.client.geocode.Placemark;
import com.google.gwt.maps.client.geom.LatLng;
import com.google.gwt.maps.client.overlay.Marker;
import com.google.gwt.user.client.ui.FlowPanel;


public class GoogleMap extends FlowPanel{
	protected MapWidget map;
	protected MarkersList<Location> locationList;
	protected MarkersList<Placemark> placemarkList;
	public GoogleMap(){
		locationList = new MarkersList<Location>();
		placemarkList = new MarkersList<Placemark>();
		buildUi();
	}
	private void buildUi() {
		LatLng boulderCity = LatLng.newInstance(40.015, -105.27);
		map = new MapWidget(boulderCity, 13);
		map.setSize("100%", "100%");
		map.setUIToDefault();
		map.setCurrentMapType(MapType.getNormalMap());
		this.add(map);
	}
	public void addMarker(Placemark placemark)
	{
		Marker loc = new Marker(placemark.getPoint());
		placemarkList.addMaker(placemark, loc);
		map.addOverlay(loc);
		map.setCenter(placemark.getPoint());
	}
	public void addMarker(Location place, LatLng point, boolean focus){
		Marker loc = new Marker(point);
		addMarker(place, loc);
		if(focus)
		  map.setCenter(point);
	}
	public void addMarker(final Location place, final Marker marker){
		locationList.addMaker(place, marker);
		map.addOverlay(marker);
		onMarkerClick(marker,place);
		marker.addMarkerClickHandler(new MarkerClickHandler(){
			@Override
			public void onClick(MarkerClickEvent event) {
				onMarkerClick(marker,place);
			}
		});
	}
	public void removeMarker(Location place)
	{
		Marker marker = locationList.removeMarker(place);
		if(marker != null)
			map.removeOverlay(marker);
	}
	public Marker getMarker(Location place)
	{
		return locationList.getMarker(place);
	}
	public Marker getMarker(Placemark placemark)
	{
		return placemarkList.getMarker(placemark);
	}
	public void onMarkerClick(Marker marker, Location place){
		if(place == null)
			System.out.println("Error: place is null in onMarkerClick");
		else
			map.getInfoWindow().open(marker, new InfoWindowContent(new InfoPanel(place, this)));
	}
	public void clearMap()
	{
		map.clearOverlays();
		placemarkList.removeAllMarkers();
		locationList.removeAllMarkers();
	}
}
